package com.qnkf.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.qnkf.code.RedisCode;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Dercsription
 * @Author Administrator
 * @CreateDate 2021/8/28 11:55
 **/
@Component
@Slf4j

public class JwtUtil {


    /**
     * 密钥
     */
    private static final String SECRET = "my_secret_makui_liufeng_qingniankuangfeng";

    /**
     * 过期时间（单位为天）
     **/
    private static final String exp = "7";

    /**
     * 生成用户token,设置token超时时间
     */
    public static String createToken(JSONObject claims) {
        long time = Long.parseLong(exp) * 24 * 60 * 60 * 1000L;
        Date expiration = new Date(System.currentTimeMillis() + time);
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        claims.put("expirationToken",expiration);
        claims.put("tokenTime",time);
        String token = JWT.create()
                .withHeader(map)// 添加头部
                //可以将基本信息放到claims中
                .withClaim("claims", JSON.toJSONString(claims))
                .withExpiresAt(expiration) //超时设置,设置过期的日期
                .withIssuedAt(new Date()) //签发时间
                .sign(Algorithm.HMAC256(SECRET)); //SECRET加密
        return token;
    }

    /**
     * 校验token并解析token
     */
    public static JSONObject verifyToken(String token) {
        DecodedJWT jwt = null;
        try {

            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            jwt = verifier.verify(token);
        } catch (Exception e) {
            log.error(e.getMessage());
            log.error("token解码异常");
            //解码异常则抛出异常
            return null;
        }
        JSONObject userModel = new JSONObject();
        Claim map = jwt.getClaim("claims");
        return JSONObject.parseObject(map.asString());
    }

    /**
     * 校验token
     * @return
     */
    public static Boolean jiexiToken(String token){
        DecodedJWT jwt = null;
        try {

            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            jwt = verifier.verify(token);
        } catch (Exception e) {
            log.error(e.getMessage());
            log.error("token解码异常");
            //解码异常则抛出异常
            return false;
        }
        return true;
    }
}
